import { ref } from "vue";
import { loadProductsAPI } from "../api/products";

export const useProducts = (categoryId = "") => {
  const page = ref(1); // 当前页码
  const loading = ref(false); // 是否加载中
  const finished = ref(false); // 是否加载完成
  const currentCategoryId = ref(categoryId); //当前需要加载数据的分类id
  const products = ref([]);

  /**
   * 
   * @param {*} needReset 是否需要重置
   * @param {*} categoryId 分类id
   */
  const loadDataFromServer = (needReset = false, categoryId = "") => {
    if (needReset) {
      // 需要重置数据
      finished.value = false;
      page.value = 1;
      products.value = [];
    }

    if (categoryId) {
      currentCategoryId.value = categoryId;
    }

    loading.value = true;
    loadProductsAPI(page.value, currentCategoryId.value).then((res) => {
      // 当页数大于总页数时，加载完成
      finished.value = res.pages < page.value;
      loading.value = false;
      products.value.push(...res.data);
      page.value++; // 加载数据成功之后也码+1
    });
  };

  return {
    loading,
    finished,
    currentCategoryId,
    products,
    loadDataFromServer,
  };
};
